local extension = Package:new("tyjR")
extension.extensionName = "hegemony_diy"
extension.game_modes_whitelist = { 'nos_heg_mode', 'new_heg_mode' }
local U = require "packages/utility/utility"
local H = require "packages/new_heg/util"

Fk:loadTranslationTable {
  ["tyjR_heg"] = "汤圆",
  ["tyjR"] = "国战-汤圆包",
}


local tyjR__guohuai = General(extension, "tyjR_heg__guohuai", "wei", 4, 4)
tyjR__guohuai:addCompanions({ "hs__xiahouyuan", "hs__zhanghe" })

local tyjR__zhangyu = fk.CreateViewAsSkill {
  name = "tyjR_heg__zhangyu",
  pattern = "jink,nullification",
  prompt = function(self)
    if Fk.currentResponsePattern ~= nil and Exppattern:Parse(Fk.currentResponsePattern):match(Fk:cloneCard("jink")) then
      return "#tyjR_heg__zhangyu-jink";
    elseif Fk.currentResponsePattern ~= nil and Exppattern:Parse(Fk.currentResponsePattern):match(Fk:cloneCard("heg__nullification")) then
      return "#tyjR_heg__zhangyu-null";
    else
      return "#tyjR_heg__zhangyu-both";
    end
  end,
  interaction = function()
    local all_names = { "jink", "nullification" }
    local names1 = {}
    if #Self:getCardIds('h') >= Self:getMaxCards() then
      table.insert(names1, 'jink')
    end
    if #Self:getCardIds('h') <= #Self:getCardIds('e') then
      table.insert(names1, 'nullification')
    end
    local names = U.getViewAsCardNames(Self, "tyjR_heg__zhangyu", names1, {})
    if #names > 0 then
      return UI.ComboBox { choices = names, all_choices = all_names }
    end
  end,
  card_filter = function(self, to_select, selected)
    if self.interaction.data then
      if self.interaction.data == "jink" then
        return #selected == 0 and Fk:currentRoom():getCardArea(to_select) == Player.Hand
      elseif self.interaction.data == "nullification" then
        return #selected == 0 and Fk:getCardById(to_select).type == Card.TypeEquip
      else
        return false
      end
    end
    return false
  end,
  view_as = function(self, cards)
    if #cards ~= 1 or not self.interaction.data then return end
    if self.interaction.data == "nullification" then
      self.interaction.data = "heg__nullification"
    end
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcards(cards)
    card.skillName = self.name
    return card
  end,
  enabled_at_play = function(self, player)
    return false
  end,
  enabled_at_response = function(self, player, response)
    if Fk.currentResponsePattern ~= nil then
      for _, name in ipairs({ "jink", "nullification" }) do
        local card = Fk:cloneCard(name)
        card.skillName = self.name
        if Exppattern:Parse(Fk.currentResponsePattern):match(card) then
          if name == "jink" then
            return #Self:getCardIds('h') >= Self:getMaxCards()
          elseif name == "nullification" then
            return #Self:getCardIds('h') <= #Self:getCardIds('e') and not response
          end
        end
      end
    end
  end,
}
tyjR__guohuai:addSkill(tyjR__zhangyu)

Fk:loadTranslationTable {
  ["tyjR_heg__guohuai"] = "郭淮",
  ["#tyjR_heg__guohuai"] = "垂问秦雍",
  ["designer:tyjR_heg__guohuai"] = "汤圆",
  ["cv:tyjR_heg__guohuai"] = "官方",
  ["illustrator:tyjR_heg__guohuai"] = "DH",

  ["tyjR_heg__zhangyu"] = "嶂御",
  [":tyjR_heg__zhangyu"] = "若你的手牌数：不大于装备区内的牌数，你可将一张装备牌当【无懈可击·国】使用；不小于手牌上限，你可将一张手牌当【闪】使用。",

  ["#tyjR_heg__zhangyu-jink"] = "嶂御：你可以将一张手牌当【闪】使用",
  ["#tyjR_heg__zhangyu-null"] = "嶂御：你可以将一张装备牌当【无懈可击·国】使用",
  ["#tyjR_heg__zhangyu-both"] = "嶂御：将装备牌当【无懈可击·国】使用，或手牌当【闪】使用",
  
  ["$tyjR_heg__zhangyu1"] = "吾已料敌布防，蜀军休想进犯！",
  ["$tyjR_heg__zhangyu2"] = "诸君依策行事，定保魏境无虞。",
  ["~tyjR_heg__guohuai"] = "岂料姜维，空手接剑。",
}


local tyjR__chenjiao = General(extension, "tyjR_heg__chenjiao", "wei", 3, 3)
tyjR__chenjiao:addCompanions({ "hs__caoren" })

local tyjR__xieshou = fk.CreateTriggerSkill {
  events = { fk.Damaged },
  name = "tyjR_heg__xieshou",
  anim_type = "drawcard",
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target:isAlive() and player ~= target 
     and not table.find(player.room.alive_players, function(p) return p.hp < target.hp end)
     and (player.faceup or not player.chained) and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local all_choices = { "tyjR_heg__xieshou_link", "tyjR_heg__xieshou_cover", "Cancel" }
    local choices = {}
    if not player.chained then
      table.insert(choices, "tyjR_heg__xieshou_link")
    end
    if player.faceup then
      table.insert(choices, "tyjR_heg__xieshou_cover")
    end
    table.insert(choices, "Cancel")
    if #choices > 0 then
      local choice = room:askForChoice(player, choices, self.name, "#tyjR_heg__xieshou-invoke::" .. target.id, false, all_choices)
      if choice ~= "Cancel" then
        self.cost_data = choice
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:doIndicate(player.id, { target.id })
    if self.cost_data and self.cost_data ~= nil then
      if self.cost_data == "tyjR_heg__xieshou_link" then
        player:setChainState(true)
        target:drawCards(2, self.name)
        if target.faceup and target:isAlive() and player:isAlive() then
          local result = room:askForSkillInvoke(target, self.name, nil, "#tyjR_heg__xieshou_turn-invoke::" .. player.id)
          if result then
            target:turnOver()
            player:drawCards(2, self.name)
          end
        end
      elseif self.cost_data == "tyjR_heg__xieshou_cover" then
        if player.faceup then
          player:turnOver()
        end
        target:drawCards(2, self.name)
        if not target.chained and target:isAlive() and player:isAlive() then
          local result = room:askForSkillInvoke(target, self.name, nil, "#tyjR_heg__xieshou_chain-invoke::" .. player.id)
          if result then
            target:setChainState(true)
            player:drawCards(2, self.name)
          end
        end
      end
    end
  end,
}
--[[
local lureTigerProhibit = fk.CreateProhibitSkill {
  name = "#lure_tiger_fake_prohibit",
  -- global = true,
  prohibit_use = function(self, player, card)
    return (player:getMark("@@lure_tiger_fake") ~= 0) or (player:getMark("@@lure_tiger-turn") ~= 0)
  end,
  is_prohibited = function(self, from, to, card)
    return (to:getMark("@@lure_tiger_fake") ~= 0) or (to:getMark("@@lure_tiger-turn") ~= 0)
  end,
}

local lureTigerHp = fk.CreateTriggerSkill {
  name = "#lure_tiger_fake_hp",
  refresh_events = { fk.PreHpRecover, fk.PreHpLost, fk.DamageInflicted },
  can_refresh = function(self, event, target, player, data)
    return target == player and ((player:getMark("@@lure_tiger_fake") ~= 0) or (player:getMark("@@lure_tiger-turn") ~= 0))
  end,
  on_refresh = function(self, event, target, player, data)
    if event == fk.DamageInflicted then
      data.damage = 0
    else
      data.num = 0
    end
    return true
  end,
}
--]]

local tyjR__qizi = fk.CreateTriggerSkill {
  name = "tyjR_heg__qizi",
  events = { fk.TargetConfirming, fk.Death },
  anim_type = "special",
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    if not (player:hasSkill(self) and H.compareKingdomWith(player, target)) then return false end
    if event == fk.TargetConfirming then
      return target ~= player and data.card.trueName == "peach" and data.from == player.id
    else
      return not player.dead
    end
  end,
  on_use = function (self, event, target, player, data)
    if event == fk.TargetConfirming then
      AimGroup:cancelTarget(data, target.id)
      return true
    else
      player.room:recover({
        who = player,
        num = 1,
        recoverBy = player,
        skillName = self.name
      })
    end
  end,
}


-- Fk:addSkill(lureTigerProhibit)
-- Fk:addSkill(lureTigerHp)
tyjR__chenjiao:addSkill(tyjR__xieshou)
tyjR__chenjiao:addSkill(tyjR__qizi)

Fk:loadTranslationTable {
  ["tyjR_heg__chenjiao"] = "陈矫",
  ["#tyjR_heg__chenjiao"] = "刚断骨鲠",
  ["designer:tyjR_heg__chenjiao"] = "汤圆",
  ["cv:tyjR_heg__chenjiao"] = "官方",
  ["illustrator:tyjR_heg__chenjiao"] = "青岛君桓",

  ["tyjR_heg__xieshou"] = "协守",
  [":tyjR_heg__xieshou"] = "每回合限一次，其他角色受到伤害后，若其的体力值为全场最小且若你未横置/叠置，你可横置/叠置并令其摸两张牌，然后其可执行另一项令你摸两张牌。",
  ["tyjR_heg__qizi"] = "弃子",
  [":tyjR_heg__qizi"] = "锁定技，与你势力相同的其他角色：1.成为你使用【桃】的目标时，取消之；2.死亡时，你回复1点体力。",

  ["#tyjR_heg__xieshou-invoke"] = "协守：是否横置或叠置以令 %dest 摸两张牌。",
  ["#tyjR_heg__xieshou_turn-invoke"] = "协守：是否将武将牌叠置以令 %dest 摸两张牌。",
  ["#tyjR_heg__xieshou_chain-invoke"] = "协守：是否将武将牌横置以令 %dest 摸两张牌。",
  ["tyjR_heg__xieshou_link"] = "横置",
  ["tyjR_heg__xieshou_cover"] = "叠置",

  ["$tyjR_heg__xieshou1"] = "此城所能守者，在你我之协力。",
  ["$tyjR_heg__xieshou2"] = "今与将军协力守城，人在则城在。",
  ["$tyjR_heg__qizi1"] = "今诸君众志成城，纵金石之力亦难破之。",
  ["$tyjR_heg__qizi2"] = "矫性谨，将军性烈，二者相佐，其利断金。",
  ["~tyjR_heg__chenjiao"] = "矫既死，则魏再无直臣哉。",
}



local tyjR__wuban = General(extension, "tyjR_heg__wuban", "shu", 4, 4)

tyjR__wuban:addCompanions({ "hs__weiyan" })
local tyjR__jintao = fk.CreateTriggerSkill {
  anim_type = "drawcard",
  name = "tyjR_heg__jintao",
  frequency = Skill.Compulsory,
  events = { fk.EventPhaseEnd },
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and target == player and player.phase == Player.Play then
      local card = Fk:cloneCard("slash")
      local card_skill = card.skill
      local status_skills = Fk:currentRoom().status_skills[TargetModSkill] or Util.DummyTable
      for _, skill in ipairs(status_skills) do
        if skill:bypassTimesCheck(player, card_skill, Player.HistoryPhase, card, nil) then return false end
      end
      return player:usedCardTimes("slash", Player.HistoryPhase) >= card_skill:getMaxUseTime(player, Player.HistoryPhase, card, nil)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local mark = player:getMark("@tyjR_heg__jintao-extraslash")
    mark = mark + 1
    room:setPlayerMark(player, "@tyjR_heg__jintao-extraslash", mark)
    player:drawCards(2, self.name)
  end,
}

local tyjR__jintao_targetmod = fk.CreateTargetModSkill {
  name = "#tyjR_heg__jintao_targetmod",
  residue_func = function(self, player, skill, scope)
    if skill.trueName == "slash_skill" and player:getMark("@tyjR_heg__jintao-extraslash") > 0 and scope == Player.HistoryPhase then
      return player:getMark("@tyjR_heg__jintao-extraslash")
    end
  end,
}

tyjR__jintao:addRelatedSkill(tyjR__jintao_targetmod)
tyjR__wuban:addSkill(tyjR__jintao)
Fk:loadTranslationTable {
  ["tyjR_heg__wuban"] = "吴班",
  ["#tyjR_heg__wuban"] = "笃进豪侠",
  ["designer:tyjR_heg__wuban"] = "汤圆",
  ["cv:tyjR_heg__wuban"] = "官方",
  ["illustrator:tyjR_heg__wuban"] = "匠人绘",

  ["tyjR_heg__jintao"] = "进讨",
  [":tyjR_heg__jintao"] = "锁定技，出牌阶段结束时，若你本阶段使用【杀】的次数不小于次数上限，你摸两张牌且此上限+1。",

  ["@tyjR_heg__jintao-extraslash"] = "进讨",
  ["#tyjR__jintao_maxhand"] = "进讨",

  ["$tyjR_heg__jintao1"] = "一雪前耻，誓报前仇！",
  ["$tyjR_heg__jintao2"] = "量敌而进，直讨吴境！",
  ["~tyjR_heg__wuban"] = "恨……杀不尽吴狗！",
}


local tyjR__furong = General:new(extension, "tyjR_heg__furong", "shu", 4, 4)

local tyjR__liechi = fk.CreateViewAsSkill {
  name = "tyjR_heg__liechi",
  anim_type = "control",
  pattern = "peach",
  prompt = "#tyjR_heg__liechi_prompt",
  card_num = 0,
  card_filter = Util.FalseFunc,
  view_as = function(self, cards)
    local card = Fk:cloneCard("peach")
    card.skillName = self.name
    return card
  end,
  before_use = function(self, player, use)
    local room = player.room
    local tot = table.filter(room.alive_players, function(p)
      return #p:getCardIds('he') > 0
    end)
    if #tot > 0 then
      local to = room:askForChoosePlayers(player, table.map(tot, Util.IdMapper), 1, 1, "tyjR_heg__liechi-choose", self.name, false, false)
      if #tot > 0 and #room:getPlayerById(to[1]):getCardIds('he') > 0 then
        local choices = {}
        local cancards = {}
        local target = room:getPlayerById(to[1])
        local cards = room:askForCardChosen(player, target, 'he', self.name, "tyjR_heg__liechi-discard::" .. target.id)
        if cards and target:isAlive() then
          room:throwCard(cards, self.name, target, player)
          if #player:getCardIds('he') > 0 and player:isAlive() then
            for _, cid in ipairs(player:getCardIds('he')) do
              if Fk:getCardById(cid).trueName == Fk:getCardById(cards).trueName then
                local yesable = true
                local peach = Fk:cloneCard("peach")
                peach.skillName = self.name
                peach:addSubcard(cid)
                if player:prohibitUse(peach) then
                  break
                end
                if use.tos ~= nil then
                  for _, pid in ipairs(use.tos) do
                    if player:isProhibited(room:getPlayerById(pid[1]), peach) then
                      yesable = false
                      break
                    end
                  end
                end
                if yesable == true then
                  table.insertIfNeed(cancards, cid)
                end
              end
            end
            if #cancards > 0 then
              table.insert(choices, "#tyjR_heg__leichi-view_as")
            end
          end
          table.insert(choices, "#tyjR_heg__leichi-remove")
          if #choices > 0 and player:isAlive() then
            local choice = room:askForChoice(player, choices, self.name)
            if choice == "#tyjR_heg__leichi-remove" then
              local isDeputy = H.inGeneralSkills(player, self.name)
              if isDeputy then
                H.removeGeneral(room, player, isDeputy == "d")
                return
              end
            else
              local get = room:askForCardsChosen(player, player, 1, 1, {card_data = { { "#tyjR_heg__liechi-pickarea", cancards } }}, self.name, "#tyjR_heg__liechi-pickcards")
              if #get > 0 then
                use.card:addSubcard(get[1])
                return
              end
            end
          end
        end
      end
    end
    return "tyjR_heg__liechi"
  end,
  enabled_at_response = function(self, player, res)
    return not res and not table.find(Fk:currentRoom().alive_players, function(p) return H.compareKingdomWith(player, p) ~= true and p.dying end)
  end,
}

local tyjR__liechi_prohibit = fk.CreateProhibitSkill {
  name = "#tyjR_heg__liechi_prohibit",
  is_prohibited = function(self, from, to, card)
    if from:hasSkill("tyjR_heg__liechi", true) then
      return table.contains(card.skillNames, "tyjR_heg__liechi") and H.compareKingdomWith(from, to) ~= true
    end
  end,
}

tyjR__liechi:addRelatedSkill(tyjR__liechi_prohibit)
tyjR__furong:addSkill(tyjR__liechi)

Fk:loadTranslationTable {
  ["tyjR_heg__furong"] = "傅肜",
  ["#tyjR_heg__furong"] = "弈世忠烈",
  ["designer:tyjR_heg__furong"] = "汤圆",
  ["cv:tyjR_heg__furong"] = "官方",
  ["illustrator:tyjR_heg__furong"] = "鬼画府",
  
  ["tyjR_heg__liechi"] = "烈斥",
  [":tyjR_heg__liechi"] = "你可弃置一名角色的一张牌，将一张同名牌当【桃】使用或移除此武将牌视为使用【桃】，你以此法使用的【桃】仅能指定与你势力相同的角色为目标。",

  ["#tyjR_heg__liechi-discard"] = "烈斥：弃置 %dest 的一张牌。",
  ["#tyjR_heg__leichi-view_as"] = "将牌当【桃】",
  ["#tyjR_heg__leichi-remove"] = "移除武将牌",
  ["#tyjR_heg__liechi_prompt"]= "烈斥：你可以弃置一名角色的一张牌，然后移除此武将牌视为使用【桃】或将一张同名牌当【桃】使用",
  ["#tyjR_heg__liechi-pickarea"] = "请选择一张牌",
  ["#tyjR_heg__liechi-pickcards"] = "烈斥：选择要被当【桃】用的牌",
  ["tyjR_heg__liechi-choose"] = "烈斥：弃置一名角色一张牌",

  ["$tyjR_heg__liechi1"] = "老夫一息尚存，吴狗便动不得主公分毫！",
  ["$tyjR_heg__liechi2"] = "吴狗何在，大汉将军傅肜在此！",
  ["~tyjR_heg__furong"] = "吴狗！何有汉将军降者！",
}

local tyjR__sunluban = General(extension, "tyjR_heg__sunluban", "wu", 3, 3, General.Female)
tyjR__sunluban:addCompanions({ "hs__sunquan" })

local tyjR__zenhui = fk.CreateTriggerSkill {
  name = "tyjR_heg__zenhui",
  events = { fk.AfterCardTargetDeclared },
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and H.compareKingdomWith(player, target) and (data.card:isCommonTrick() or data.card.trueName == 'slash') 
     and table.every(player.room:getOtherPlayers(target), function(p) return #target:getCardIds('e') >= #p:getCardIds('e') end)
     and data.card.trueName ~= "threaten_emperor"
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = room:getUseExtraTargets(data)
    if #targets == 0 then return false end
    local tos = room:askForChoosePlayers(player, targets, 1, 1, "#tyjR__zenhui_target:::" .. data.card:toLogString(), self.name, true)
    if #tos > 0 then
      self.cost_data = tos[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local tos = self.cost_data
    table.insert(data.tos, { tos })
    room:sendLog { type = "#AddTargetsBySkill", from = target.id, to = { tos }, arg = self.name, arg2 = data.card:toLogString() }
    local to = room:getPlayerById(tos)
    if to:isAlive() and target:isAlive() and #target:getCardIds('he') > 0 then
      local card = room:askForCardChosen(to, target, "he", self.name, "#tyjR__zenhui_discard")
      room:throwCard({ card }, self.name, target, player)
    end
  end,
}

local tyjR__jiaojin_active = fk.CreateActiveSkill {
  name = "#tyjR_heg__jiaojin_active",
  card_num = 1,
  visible = false,
  mute = true,
  card_filter = function(self, to_select, selected, targets)
    local tos = Self:getMark("tyjR_heg__jiaojin_from-phase")
    if tos ~= 0 then
      return #selected == 0 and Fk:getCardById(to_select).type == Card.TypeEquip and
          U.canMoveCardIntoEquip(Fk:currentRoom():getPlayerById(tos), to_select, true)
    end
  end,
}

local tyjR__jiaojin = fk.CreateTriggerSkill {
  name = "tyjR_heg__jiaojin",
  anim_type = "offensive",
  events = { fk.DamageInflicted },
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      return target == player and data.from and data.from:isAlive() and #player:getCardIds('he') > 0
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "tyjR_heg__jiaojin_from-phase", data.from.id)
    local success, dat = player.room:askForUseActiveSkill(player, "#tyjR_heg__jiaojin_active", "#tyjR_heg__jiaojin-invoke::" .. data.from.id, true)
    if success then
      self.cost_data = dat
      room:setPlayerMark(player, "tyjR_heg__jiaojin_from-phase", 0)
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = data.from
    U.moveCardIntoEquip(room, to, self.cost_data.cards[1], self.name, true, player)
    return true
  end,
}

tyjR__sunluban:addSkill(tyjR__zenhui)
tyjR__jiaojin:addRelatedSkill(tyjR__jiaojin_active)
tyjR__sunluban:addSkill(tyjR__jiaojin)

Fk:loadTranslationTable {
  ["tyjR_heg__sunluban"] = "孙鲁班",
  ["#tyjR_heg__sunluban"] = "为虎作伥",
  ["designer:tyjR_heg__sunluban"] = "汤圆",
  ["cv:tyjR_heg__sunluban"] = "官方",
  ["illustrator:tyjR_heg__sunluban"] = "FOOLTOWN",

  ["tyjR_heg__zenhui"] = "谮毁",
  [":tyjR_heg__zenhui"] = "与你势力相同的角色使用【杀】或普通锦囊牌时，若其装备区内的牌数为全场最多，你可为此牌指定一个额外目标，然后此额外目标弃置此牌使用者的一张牌。",
  ["tyjR_heg__jiaojin"] = "骄矜",
  [":tyjR_heg__jiaojin"] = "当你受到伤害时，你可将一张装备牌置入伤害来源的装备区（替换原装备），防止之。",
  ["#tyjR_heg__jiaojin_active"] = "骄矜",

  ["#tyjR__zenhui_target"] = "谮毁：你可为 %arg 指定一个额外的目标",
  ["#tyjR__zenhui_discard"] = "谮毁：弃置其一张牌",
  ["#tyjR_heg__jiaojin-invoke"] = "骄矜：你可将一张装备牌置于 %dest 的装备区内，防止此伤害",

  ["$tyjR_heg__zenhui1"] = "你可别不识抬举！",
  ["$tyjR_heg__zenhui2"] = "你也休想置身事外！",
  ["$tyjR_heg__jiaojin1"] = "是谁借给你的胆子？",
  ["$tyjR_heg__jiaojin2"] = "就凭你、还想算计于我？！",
  ["~tyjR_heg__sunluban"] = "本公主，何罪之有？",
}


local tyjR__panshu = General(extension, "tyjR_heg__panshu", "wu", 3, 3, General.Female)
tyjR__panshu:addCompanions({ "hs__sunquan" })

local tyjR__jinzhi = fk.CreateTriggerSkill {
  name = "tyjR_heg__jinzhi",
  anim_type = "drawcard",
  events = { fk.AfterCardsMove },
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.CardUseFinished then
        return target == player and data.card.type == Card.TypeEquip
      else
        local equipnum = #player:getCardIds("e")
        for _, move in ipairs(data) do
          for _, info in ipairs(move.moveInfo) do
            if move.from == player.id and info.fromArea == Card.PlayerEquip then
              equipnum = equipnum + 1
            elseif move.to == player.id and move.toArea == Card.PlayerEquip then
              equipnum = equipnum - 1
            end
          end
        end
        if #player:getCardIds("e") ~= equipnum then
          local ecards = player:getCardIds("e")
          --[[if #ecards == 0 then
            return true
          else]]
          if #ecards ~= 0 then
            local suits = {}
            for _, cid in ipairs(player:getCardIds("e")) do
              local c = Fk:getCardById(cid)
              if table.contains(suits, c.suit) then
                return false
              else
                table.insertIfNeed(suits, c.suit)
              end
            end
            return true
          end
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local to = room:askForChoosePlayers(player, table.map(room.alive_players, Util.IdMapper), 1, 1, "#tyjR__jinzhi-invoke", self.name, true, false)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    room:doIndicate(player.id, { self.cost_data })
    if to:isAlive() then
      room:drawCards(to, 1, self.name)
    end
  end,
}

local tyjR__weiyi = fk.CreateTriggerSkill {
  name = "tyjR_heg__weiyi",
  anim_type = "control",
  events = { fk.BeforeDrawCard },
  can_trigger = function(self, event, target, player, data)
    return H.compareKingdomWith(player, target) and #target:getCardIds('e') < #player:getCardIds('e') and
        player:hasSkill(self) and data.skillName ~= self.name and data.num > 0 and target.phase == Player.Draw
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    return room:askForSkillInvoke(player, self.name, nil, "#tyjR_heg__weiyi-invoke::" .. target.id .. ":" .. data.num)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:drawCards(player, data.num, self.name)
    if player:isAlive() and target:isAlive() and #player:getCardIds('he') > 0 then
      local cardsm = room:askForCard(player, math.min(#player:getCardIds('he'), data.num),
        math.min(#player:getCardIds('he'), data.num), true, self.name, false, ".", "#tyjR_heg__weiyi-give::" .. target.id .. ":" .. data.num)
      if #cardsm > 0 then
        room:moveCardTo(cardsm, Player.Hand, target, fk.ReasonGive, self.name, nil, false, player.id)
      end
    end
    data.num = 0
  end,
}

tyjR__panshu:addSkill(tyjR__jinzhi)
tyjR__panshu:addSkill(tyjR__weiyi)

Fk:loadTranslationTable {
  ["tyjR_heg__panshu"] = "潘淑",
  ["#tyjR_heg__panshu"] = "婉转燕尔",
  ["designer:tyjR_heg__panshu"] = "汤圆",
  ["cv:tyjR_heg__panshu"] = "官方",
  ["illustrator:tyjR_heg__panshu"] = "君桓文化",

  ["#tyjR_heg__jinzhi"] = "锦织",
  ["tyjR_heg__jinzhi"] = "锦织",
  [":tyjR_heg__jinzhi"] = "当你装备区内牌的数量变化后，若你装备区内有牌且花色均不相同，你可令一名角色摸一张牌。",
  ["tyjR_heg__weiyi"] = "威仪",
  [":tyjR_heg__weiyi"] = "与你势力相同的角色的摸牌阶段，若其装备区内的牌数小于你，你可改为此阶段你执行摸牌并交给其等量牌。",

  ["#tyjR__jinzhi-invoke"] = "锦织：你可以令一名角色摸一张牌",
  ["#tyjR_heg__weiyi-invoke"] = "威仪：你可以改为你执行摸牌并交给其等量的牌",
  ["#tyjR_heg__weiyi-give"] = "威仪：请交给 %dest %arg 张牌",

  ["$tyjR_heg__jinzhi1"] = "织锦为旗，以扬威仪。",
  ["$tyjR_heg__jinzhi2"] = "坐而织锦，立则为仪。",
  ["$tyjR_heg__weiyi1"] = "无威仪者，不可奉社稷。",
  ["$tyjR_heg__weiyi2"] = "有威仪者，进止雍容。",
  ["~tyjR_heg__panshu"] = "本为织女，幸蒙帝垂怜……",
}

local tyjR__huangfusong = General(extension, "tyjR_heg__huangfusong", "qun", 4, 4)

local tyjR__shiji = fk.CreateTriggerSkill {
  name = "tyjR_heg__shiji",
  events = { fk.AfterCardsMove, fk.EventPhaseStart },
  anim_type = "offensive",
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.AfterCardsMove then
        for _, move in ipairs(data) do
          if #move.moveInfo > 0 then
            if move.proposer and move.proposer == player.id and move.moveReason == fk.ReasonDiscard and move.from then
              for _, info in ipairs(move.moveInfo) do
                if table.contains({ Card.PlayerEquip, Card.PlayerHand }, info.fromArea) then
                  return true
                end
              end
            end
          end
        end
      end
    end
    if event == fk.EventPhaseStart then
      return player:getMark('@@tyjR_heg__shiji_used') ~= 0
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AfterCardsMove then
      return room:askForSkillInvoke(player, self.name)
    elseif event == fk.EventPhaseStart then
      room:setPlayerMark(player, '@@tyjR_heg__shiji_used', 0)
      if player:isAlive() then
        local all_choices = { "#tyjR_heg__shiji_use", "#tyjR_heg__shiji_fire" }
        local choice = {}
        local ids = {}
        room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function(e)
          for _, move in ipairs(e.data) do
            if move.toArea == Card.DiscardPile and move.moveReason == fk.ReasonDiscard then
              for _, info in ipairs(move.moveInfo) do
                table.insertIfNeed(ids, info.cardId)
              end
            end
          end
          return false
        end, Player.HistoryTurn)
        ids = table.filter(ids, function(id) return room:getCardArea(id) == Card.DiscardPile end)
        if #ids > 0 then
          table.insert(choice, "#tyjR_heg__shiji_use")
        end
        if #table.filter(room.alive_players, function(t)
              return U.canUseCardTo(room, player, t, Fk:cloneCard("fire_attack"))
            end) > 0 then
          table.insert(choice, "#tyjR_heg__shiji_fire")
        end
        if #choice > 0 then
          local choice = room:askForChoice(player, choice, self.name, "#tyjR_heg__shiji_chooseone", true, all_choices)
          if choice then
            self.cost_data = choice
            return true
          end
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AfterCardsMove then
      room:setPlayerMark(player, "@@tyjR_heg__shiji_used", 1)
    elseif event == fk.EventPhaseStart then
      if player:isAlive() then
        local choice = self.cost_data
        if choice == "#tyjR_heg__shiji_use" then
          local ids = {}
          room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function(e)
            for _, move in ipairs(e.data) do
              if move.toArea == Card.DiscardPile and move.moveReason == fk.ReasonDiscard then
                for _, info in ipairs(move.moveInfo) do
                  table.insertIfNeed(ids, info.cardId)
                end
              end
            end
            return false
          end, Player.HistoryTurn)
          ids = table.filter(ids, function(id) return room:getCardArea(id) == Card.DiscardPile end)
          if #ids > 0 then
            local to = room:askForChoosePlayers(player, table.map(player.room:getOtherPlayers(player), Util.IdMapper), 1, 1, "#tyjR_heg__shiji_chooseto", self.name, false)
            if #to > 0 then
              U.askForUseRealCard(room, room:getPlayerById(to[1]), ids, nil, self.name, "#tyjR_heg__shiji_use-invoke", { expand_pile = ids, extra_use = true }, false)
            end
          end
        elseif choice == "#tyjR_heg__shiji_fire" then
          U.askForUseVirtualCard(room, player, "fire_attack", nil, self.name, "#tyjR_heg__shiji_fire-invoke", true, false, false, false, nil, false)
        end
      end
    end
  end,
}

tyjR__huangfusong:addSkill(tyjR__shiji)

Fk:loadTranslationTable {
  ["tyjR_heg__huangfusong"] = "皇甫嵩",
  ["#tyjR_heg__huangfusong"] = "营火溃螟",
  ["designer:tyjR_heg__huangfusong"] = "汤圆",
  ["cv:tyjR_heg__huangfusong"] = "官方",
  ["illustrator:tyjR_heg__huangfusong"] = "鬼画府",

  ["tyjR_heg__shiji"] = "势击",
  [":tyjR_heg__shiji"] = "当你弃置任意角色的牌后，你可以令你于下个阶段开始时选择一项：1.令一名其他角色使用一张本回合因弃置而进入弃牌堆的牌；2.视为使用一张【火攻】。",

  ["#tyjR_heg__shiji_use"] = "令其他角色使用牌",
  ["#tyjR_heg__shiji_use-invoke"] = "势击：使用其中一张牌。",
  ["#tyjR_heg__shiji_chooseto"] = "势击：选择要使用牌的角色",
  ["#tyjR_heg__shiji_chooseone"] = "势击：你可以选择一项执行",
  [":#tyjR_heg__shiji_use"] = "令一名其他角色使用一张本回合因弃置进入弃牌堆的牌",
  ["#tyjR_heg__shiji_fire"] = "使用【火攻】",
  [":#tyjR_heg__shiji_fire"] = "视为使用一张【火攻】",
  ["#tyjR_heg__shiji_fire-invoke"] = "势击：视为使用一张【火攻】",
  ["@@tyjR_heg__shiji_used"] = "势击",

  ["$tyjR_heg__shiji1"] = "敌军依草结营，正犯兵家大忌！",
  ["$tyjR_heg__shiji2"] = "兵法所云火攻之计，正合此时之势！",
  ["~tyjR_heg__huangfusong"] = "力有所能，臣必为也……",
}


local tyjR__gongsundu = General(extension, "tyjR_heg__gongsundu", "qun", 4, 4)

local tyjR__zhenzhe = fk.CreateTriggerSkill {
  name = "tyjR_heg__zhenzhe",
  events = { fk.Damage },
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      return data.card and ((data.card.trueName == 'slash') or data.card.name == "duel") and data.to and data.to:isAlive()
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local tos = table.filter(room.alive_players, function(p) return data.to:inMyAttackRange(p) and #p:getCardIds('h') ~= math.max(data.to.hp, 0) end)
    if #tos > 0 then
      local to = room:askForChoosePlayers(player, table.map(tos, Util.IdMapper), 1, 1, "#tyjR__zhenzhe-invoke::" .. data.to.id .. ":" .. data.to.hp, self.name, true, true)
      if #to > 0 then
        self.cost_data = to[1]
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    room:doIndicate(player.id, { to.id })
    local num = math.max(data.to.hp, 0)
    if to:isAlive() and #to:getCardIds('h') ~= num then
      local n = #to:getCardIds('h') - num
      if n > 0 then
        local cards = room:askForDiscard(to, n, n, false, self.name, false, '.', "#tyjR__zhenzhe-discard:::" .. n, false, false)
        if #cards > 0 and to:isAlive() then
          room:recover({
            who = to,
            num = 1,
            recoverBy = player,
            skillName = self.name
          })
        end
      elseif n < 0 then
        player:drawCards(-n, self.name)
      end
    end
  end,
}

tyjR__gongsundu:addSkill(tyjR__zhenzhe)
Fk:loadTranslationTable {
  ["tyjR_heg__gongsundu"] = "公孙度",
  ["#tyjR_heg__gongsundu"] = "威戾海东",
  ["designer:tyjR_heg__gongsundu"] = "汤圆",
  ["cv:tyjR_heg__gongsundu"] = "官方",
  ["illustrator:tyjR_heg__gongsundu"] = "匠人绘",

  ["tyjR_heg__zhenzhe"] = "振疆",
  [":tyjR_heg__zhenzhe"] = "当你使用【杀】或【决斗】对其他角色造成伤害后，你可令其攻击范围内的一名角色将手牌数摸或弃至其体力值，若其以此法弃牌，其回复1点体力。",

  ["#tyjR__zhenzhe-invoke"] = "振疆：你可以令 %dest 攻击范围内的一名角色将手牌数调整至 %arg 张",
  ["#tyjR__zhenzhe-discard"] = "振疆：请弃置 %arg 张牌，然后你回复1点体力",
  ["@tyjR_heg__zhenzhe-draw"] = "摸牌",
  ["@tyjR_heg__zhenzhe-dis"] = "弃牌",
  ["@tyjR_heg__zhenzhe-recover"] = "回复",

  ["$tyjR_heg__zhenzhe1"] = "名震千里，泽被海东。",
  ["$tyjR_heg__zhenzhe2"] = "施威除暴，上下咸服。",
  ["~tyjR_heg__gongsundu"] = "为何都不愿出仕！",
}

return extension
